<template>
    <div class="app-container">
        <el-form :model="formData" ref="formDataForm" :inline="true" label-width="68px">
            <el-form-item label="店铺" prop="status" v-if="checkPermi(['searchTenantID'])">
                <el-select v-model="formData.tenantId" placeholder="请选择店铺" clearable filterable>
                    <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName"
                        :value="dict.tenantId" />
                </el-select>
            </el-form-item>

            <el-form-item label="员工昵称" prop="userName">
                <el-input v-model="userName" placeholder="请输入员工昵称" clearable></el-input>
            </el-form-item>
            <el-form-item label="月份筛选" prop="accountId">
                <el-date-picker @change="timeSearch" v-model="month" type="month" placeholder="选择月份" format="yyyy-MM"
                    value-format="yyyy-MM">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">
                    搜索
                </el-button>
                <el-button :loading="expertLoading" type="warning" icon="el-icon-download" @click="handleExpert">
                    导出
                </el-button>
            </el-form-item>
        </el-form>
        <div class="table_box table_box_new">
            <!-- 收号总数  总库存  出号总和   本月亏损-->
            <el-table  v-loading="loading" stripe :data="cardSecretList" border 
                :summary-method="getSummaries"   height="calc(100vh - 190px)" show-summary>
                <el-table-column fixed prop="userName" label="员工" minWidth="140"></el-table-column>
                <el-table-column width="105" prop="buyNumber" label="收号总数" sortable>
                    <template slot-scope="scope">
                        <span style="color: #409EFF; cursor: pointer;"
                            @click="showDetail(scope.row, 'buyNumberComment')">
                            {{ scope.row.buyNumber }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column width="105" prop="afterNumber" label="本月售后" sortable></el-table-column>
                <el-table-column prop="buyAverage" label="平均每日收号" sortable width="130"></el-table-column>
                <el-table-column width="105" prop="stock" label="总库存" sortable>
                    <template slot-scope="scope">
                        <span style="color: #409EFF; cursor: pointer;" @click="showDetail(scope.row, 'stockComment')">
                            {{ scope.row.stock }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column width="110" prop="cost" label="总成本" sortable></el-table-column>
                <el-table-column width="110" prop="stockUnitPrice" label="平均单价" sortable></el-table-column>
                <el-table-column width="110" prop="unsalableNumber" label="滞销数量" sortable>
                         <template slot-scope="scope">
                        <span style="color: #409EFF; cursor: pointer;"
                            @click="showDetail(scope.row, 'unsalableComment')">
                            {{ scope.row.unsalableNumber }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column width="110" prop="saleNumber" label="已出号" sortable>
                    <template slot-scope="scope">
                        <span style="color: #409EFF; cursor: pointer;"
                            @click="showDetail(scope.row, 'saleNumberComment')">
                            {{ scope.row.saleNumber }}
                        </span>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="totalSales" label="出号总和" sortable></el-table-column> -->

                <el-table-column width="105" prop="profitUnitPrice" label="平均利润" sortable></el-table-column>
                <el-table-column width="105" prop="profit" label="结算利润" sortable></el-table-column>

                <el-table-column width="110" prop="loss" label="本月亏损" sortable>
                    <template slot-scope="scope">
                        <span style="color: #409EFF; cursor: pointer;" @click="showDetail(scope.row, 'lossComment')">
                            {{ scope.row.loss }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column width="110" prop="highestSalesGame" label="销量最高"></el-table-column>
                <el-table-column width="110" prop="highestProfitGame" label="利润最高"></el-table-column>
                <el-table-column width="110" prop="unsalableGame" label="滞销最高"></el-table-column>
            </el-table>
        </div>

        <!-- 详情弹窗 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
            <div class="table_box ">
                员工: {{ detailUserName }}
                <div style="margin-left: 40px;margin-top: 4px;">
                    <div style="white-space: pre-line;line-height: 1.6;" v-if="detailData" v-html="detailData"></div>
                    <div style="text-align: center;padding: 30px 0;" v-else>暂无数据</div>
                </div>
                <!-- <el-table :data="detailData" border style="width: 100%">
                <el-table-column v-for="col in detailColumns" :key="col.prop" :prop="col.prop" :label="col.label"></el-table-column>
            </el-table> -->
                <div slot="footer" class="dialog-footer">
                    <!-- <el-button @click="dialogVisible = false">关闭</el-button> -->
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { employeeList, employeeExport } from "@/api/system/dept";
import moment from "moment";
export default {
    data() {
        return {
            loading: false,
            month: '',
            formData: {
                beginTime: '',
                endTime: ''
            },
            userName: '',
            cardSecretList: [],
            // 弹窗相关
            dialogVisible: false,
            dialogTitle: '',
            detailData: '',
            detailUserName: '',
            expertLoading:false
        }
    },
    computed: {
        userInfo() {
            return this.$store.getters.userInfo;
        },

        tenantList() {
            return this.$store.getters.tenantList;
        },
    },

    methods: {
        getEmployeeList() {
            this.loading = true;
            employeeList(this.formData).then((response) => {
                this.cardSecretList = response.rows;
                 if (this.userName) {
                    this.userNameSelect(this.userName)
                 }
                this.loading = false;
            });
        },
        userNameSelect(val) {
            //过滤列表
            this.cardSecretList = this.cardSecretList.filter(item => item.userName.indexOf(val) > -1)
        },
        handleSearch() {
          
            this.getEmployeeList()
        },
        handleExpert() {
            this.expertLoading = true;
            employeeExport(this.formData).then((res) => {
                let msg ='员工月度统计'+ this.formData.beginTime + '至'+ this.formData.endTime 
                this.$download.downloadFile(res, msg);
                this.expertLoading = false;
                this.$message.success('导出成功');
            }).finally(() => {
                 this.expertLoading = false;
});
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = new Array(columns.length).fill('');
            if (!Array.isArray(columns) || columns.length === 0) return sums;

            const noSumProps = ['highestSalesGame', 'highestProfitGame', 'unsalableGame'];

            const averageProps = ['profitUnitPrice', 'stockUnitPrice'];
             // 第一列显示总计
            sums[0] = '总计';

              // 如果没有数据，直接返回（其它列保持空）
                if (!Array.isArray(data) || data.length === 0) {
                    return sums;
                }

                    const colTotals = {};
                      columns.forEach(col => {
        const prop = col.property;
        if (!prop) return;
        colTotals[prop] = data.reduce((acc, row) => {
            const v = Number(row[prop]);
            return acc + (isNaN(v) ? 0 : v);
        }, 0);
    });

            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '总计';
                    return;
                }
                if (noSumProps.includes(column.property)) {
                    sums[index] = '';
                    return;
                }
                if (averageProps.includes(column.property)) {
                    switch (column.property) {
                        case 'profitUnitPrice': {
                            // 2. profitUnitPrice：结算利润 除 已出号
                            const totalProfit = data.reduce((sum, item) => {
                                const value = Number(item.profit);
                                return sum + (isNaN(value) ? 0 : value);
                            }, 0);
                            const soldTotal = data.reduce((sum, item) => {
                                const count = Number(item.saleNumber || 0);
                                return sum + (isNaN(count) ? 0 : count);
                            }, 0);
                            const unitPrice = soldTotal > 0 ? totalProfit / soldTotal : 0;
                            sums[index] = unitPrice.toFixed(2);
                            break;
                        }
                        case 'stockUnitPrice': {
                            // 3. stockUnitPrice：总成本 ÷ 总库存
                            const totalCost = data.reduce((sum, item) => {
                                const cost = Number(item.cost);
                                return sum + (isNaN(cost) ? 0 : cost);
                            }, 0);
                            const totalStock = data.reduce((sum, item) => {
                                const qty = Number(item.stock);
                                return sum + (isNaN(qty) ? 0 : qty);
                            }, 0);
                            // 处理除数为0
                            const unitCost = totalStock > 0 ? totalCost / totalStock : 0;
                            sums[index] = unitCost.toFixed(2);
                            break;
                        }
                    }
                } else {
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        if (String(sums[index]).includes('.')) {
                            sums[index] = sums[index].toFixed(2);
                        } else {
                            sums[index] = sums[index]
                        }

                    } else {
                        sums[index] = '';
                    }
                }
            });

            return sums;
        },
        // 显示详情弹窗
        showDetail(row, type) {
            this.dialogVisible = true;
            this.detailUserName = row.userName;
            switch (type) {
                case 'buyNumberComment':
                    this.dialogTitle = '收号总数详情';
                    this.detailData = row.buyNumberComment;

                    break;
                case 'stockComment':
                    this.dialogTitle = '总库存详情';
                    this.detailData = row.stockComment;
                    break;
                case 'saleNumberComment':
                    this.dialogTitle = '出号总和详情';
                    this.detailData = row.saleNumberComment;
                    break;
                case 'lossComment':
                    this.dialogTitle = '本月亏损详情';
                    this.detailData = row.lossComment;
                    break;
                      case 'unsalableComment':
                    this.dialogTitle = '滞销数量详情';
                    this.detailData = row.unsalableComment;
                    break;
                default:
                    this.dialogVisible = false;
            }
        },
        timeSearch(val) {
            this.formData.beginTime = moment(val)
                .date(1) // 设置为当月1号
                .format('YYYY-MM-DD 00:00:00'); // 格式化为字符串

            // 2. 获取下个月1号（2025-09-01）
            this.formData.endTime = moment(val).add(1, 'month') // 加1个月
                .date(1) // 设置为下个月1号
                .format('YYYY-MM-DD 00:00:00'); // 格式化为字符串
        }
    },

    mounted() {
        this.formData.beginTime = moment().date(1).format('YYYY-MM-DD 00:00:00')
        this.formData.endTime = moment().add(1, 'month').date(1).format('YYYY-MM-DD 00:00:00'); // 格式化为字符串
        this.month = moment().format('YYYY-MM');
        this.getEmployeeList();
    },
}

</script>
<style scoped lang="scss">
.table_box_new {
    background-color: #fff;
    border-radius: 4px;
    height: calc(100vh - 190px);
}

.el-table {
    overflow: visible !important;
}
</style>